package com.cefa.finance.service;

import com.cefa.finance.dao.*;
import com.cefa.finance.model.*;
import com.cefa.finance.result.ResultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class RepaymentInfoService {

    private final static Logger logger = LoggerFactory.getLogger(RepaymentInfoService.class);

    @Autowired
    private RepaymentRecordRepository repaymentRecordRepository;

    @Autowired
    private ContractMapper contractMapper;

    @Transactional("transactionManagerPrimary")
    public ResultModel addPaymentRecord(RepaymentRecord repaymentRecord) {
        RepaymentRecord record = repaymentRecordRepository.save(repaymentRecord);
        return ResultModel.OK(record);
    }

    @Transactional("transactionManagerPrimary")
    public ResultModel deletePaymentRecord(RepaymentRecord repaymentRecord) {
        repaymentRecordRepository.delete(repaymentRecord.getId());
        return ResultModel.OK();
    }

    public ResultModel listPaymentInfo(String searchText, Integer pageNo, Integer pageCount) {

        ArrayList<ContractModel> allResult = new ArrayList<>();
        ArrayList<ContractModel> certainContracts = new ArrayList<>();
        HashMap<String, Object> resultMap = new HashMap<>();

        List<ContractModel> allContracts = contractMapper.findAllRepaymentContracts();

        for (ContractModel contract : allContracts) {
            allResult.add(contract);
            if (searchText != null && !"".equals(searchText) && contract.getTenantryName() != null && contract.getVin() != null && contract.getPhone() != null) {
                if (contract.getTenantryName().contains(searchText) || contract.getVin().contains(searchText)) {
                    certainContracts.add(contract);
                    String s;
                }
            }
        }

        if (searchText != null && !"".equals(searchText)) {
            allResult = certainContracts;
        }

        if (pageNo != null && pageCount != null) {
            resultMap.put("totalPage", (allResult.size() - 1) / pageCount + 1);
            allResult = new ArrayList<>(allResult.subList((pageNo - 1) * pageCount, pageCount * pageNo > allResult.size() ? allResult.size() : pageCount * pageNo));
        }
        resultMap.put("contracts", allResult);
        return ResultModel.OK(resultMap);
    }
}


















